import Vue from 'vue';
// 假设 eventBus 已在全局定义，若未定义需补充：
// export const eventBus = new Vue();
import typeofMsg from '../utils/typeofMsg';
import {
	processReceivedMessage,
	initializeData
} from '../utils/chatList.js';

export default {
	namespaced: true,
	state: {
		markers:[],
		user: null,
		sendUser:null,
		chatList: [],
		publicMessageList:[],
		currentSession: [],
		ws: null,
		reconnectTimer: null, // 存储定时器ID
		location: null, // 接听位置
		senderLocation: null,
		locationMessage: [],
		count: 1, // 重连次数基数
		isFly: false,
		sessions: [],
		messageQueue: [],
		audioContext: null,
		joinGroup: null,
		stateConfig: null,
		onlineUserCount:0,
		onlineShopCount:0,
		address:"",
		mapScale:null
	},

	mutations: {
		// 修改 WebSocket 实例
		SET_WS(state, value) {
			Vue.set(state, 'ws', value);
		},
	SET_CHATLIST(state, value) {
	  const newData = Array.isArray(value) ? value : [];
		  state.chatList = [ ...newData];
	   state.chatList.sort((a, b) => b.timestamp - a.timestamp);
	},
		// 修改定位信息
		SET_location(state, value) {
			Vue.set(state, 'location', value);
		},
		// 修改发送者位置
		SET_senderLocation(state, value) {
			Vue.set(state, 'senderLocation', value);
		},
		// 修改用户信息
		SET_user(state, value) {
			Vue.set(state, 'user', value);
		},
		SET_publicMessageList(state, value){
	
			state.publicMessageList=value
			
		},
		SET_markers(state,value){
			state.markers=value
		},
		SET_onlineUserCount(state,value){
			state.onlineUserCount=value
		},
		SET_address(state,value){

			state.address=value
		},
		SET_mapScale(state,value){
			state.mapScale=value
		},
		SET_onlineShopCount(state,value){
			state.onlineShopCount=value
		},
		// 修改飞行状态
		SET_isFly(state, value) {
			state.isFly = value;
		},
		SET_messageQueue(state, value) {
		
			const newQueue = [...state.messageQueue, value]
			Vue.set(state, 'messageQueue', newQueue);
		
		},

		// 初始化本地存储数据
		INIT_STORAGE_DATA(state, storageData) {
			Object.keys(storageData).forEach(key => {
				if (state.hasOwnProperty(key)) {
					state[key] = storageData[key];
				}
			});
		
		},
		// 记录重连延迟时间（不启动定时器，仅存状态）
		scheduleReconnect(state) {
			if (state.reconnectTimer) return;
			const delay = Math.min(2 ** state.count * 1000, 8000); // 指数退避重连
			state.reconnectTimer = delay;
		},
		// 清除重连定时器
		clearReconnectTimer(state) {
			if (state.reconnectTimer) {
				clearTimeout(state.reconnectTimer);
				state.reconnectTimer = null;
			}
		},
		// 关闭已存在的WebSocket连接
		closeExistingWebSocket(state) {
			if (state.ws) {
				uni.closeSocket();
				state.ws = null;
			}
		},
		// 更新重连次数
		SET_COUNT(state, value) {
			state.count = value;
		},
		// 记录定时器ID（新增）
		SET_RECONNECT_TIMER(state, timerId) {
			state.reconnectTimer = timerId;
		},
		// 更新加入群组信息
		SET_JOIN_GROUP(state, data) {
			state.joinGroup = data;
		},
		SET_stateConfig(state,data){
			Vue.set(state,'stateConfig',data)
		}
	},

	actions: {
			
		async initializeChatList({
			commit,
			state
		}) { // 从参数中解构 state
			try {
			const data = await initializeData();
				commit('SET_CHATLIST', data);
			} catch (error) {
				console.error("initializeChatList 执行失败:", error); // 捕获所有可能的错误
			}
		},
	async	setupWebSocketListeners({
			commit,
			state,
			dispatch
		}) {
			uni.onSocketOpen(() => {
				console.log('WebSocket连接已打开');
				commit('SET_COUNT', 1); // 重置重连次数
				uni.$emit('onlineStatusChanged', true);
				// 连接成功后可处理消息队列
				dispatch('processMessageQueue');
			});

			// 连接关闭回调
			uni.onSocketClose((res) => {
				console.log('WebSocket连接关闭:', res);
				uni.$emit('onlineStatusChanged', false);
				commit('scheduleReconnect'); // 触发重连计划（仅记录延迟）
				dispatch('startReconnectTimer'); // 启动重连定时器
			});

			// 连接错误回调
			uni.onSocketError((error) => {
				console.error('WebSocket连接错误:', error);
				uni.$emit('onlineStatusChanged', false);
				commit('scheduleReconnect');
				dispatch('startReconnectTimer');
			});

			// 接收消息回调
			uni.onSocketMessage(async (msg) => {
				try {
					const msgJsoned = JSON.parse(msg.data);
					console.log('收到了消息', msgJsoned);
					switch (msgJsoned.type) {
						case 'joinGroup':
							commit('SET_JOIN_GROUP', msgJsoned);
							uni.$emit('joinGroup', msgJsoned);
							break;
						case 'msg':
							if (msgJsoned.data.length > 0) {
								uni.$emit('readmessages', msgJsoned.data);
								const msg= await processReceivedMessage(msgJsoned.data, state.user) 
							
								commit('SET_CHATLIST', msg);
								typeofMsg(msgJsoned.data)
							}

							break;
						case 'onLine':
							console.log('收到在线通知:', msgJsoned);
							uni.$emit('onLineNoti', msgJsoned);
							break;
						default:
							break;
					}
				} catch (e) {
					console.error('解析WebSocket消息失败:', e);
				}
			});
		},

		// 启动重连定时器
		startReconnectTimer({
			commit,
			state,
			dispatch
		}) {
			console.log('计时.........')
			// 若已有定时器，先清除
			if (typeof state.reconnectTimer === 'number') {
				clearTimeout(state.reconnectTimer);
			}
			// 从state获取延迟时间（由scheduleReconnect设置）
			const timer = setTimeout(() => {
				dispatch('reconnect'); // 执行重连
				commit('SET_COUNT', state.count + 1); // 递增重连次数
			}, state.reconnectTimer);
			commit('SET_RECONNECT_TIMER', timer); // 记录定时器ID
		},

		// 建立WebSocket连接
		async connectWebSocket({
			commit,
			dispatch
		}, {
			location,
			userTel
		}) {
			// 前置清理
			commit('clearReconnectTimer');
			commit('closeExistingWebSocket');

			const query = {
				userTel: userTel,
				location: JSON.stringify(location)
			};

			try {
				const ws = await uniCloud.connectWebSocket({
					name: 'web',
					query: query
				});
				commit('SET_WS', ws); // 保存WebSocket实例
				dispatch('setupWebSocketListeners'); // 注册监听器（用dispatch调用action）
				return true;
			} catch (error) {
				console.error('WebSocket连接失败:', error);
				uni.showToast({
					title: '网络故障，无法连接',
					icon: 'error'
				});
				return false;
			}
		},

		// 重连WebSocket
		async reconnect({
			state,
			dispatch
		}) {
			console.log(state.ws);
			// 若已有连接或无必要参数，不重连
			if (state.ws === 1 || !state.location || !state.user?.userTel) {
				return;
			}
			// 调用连接方法
			await dispatch('connectWebSocket', {
				location: state.location,
				userTel: state.user.userTel
			});
		},

		// 处理消息队列（连接成功后发送缓存的消息）
		processMessageQueue({
			state
		}) {
			if (state.messageQueue.length === 0 || state.ws.readyState !== 1) return;
	
			// 遍历发送队列中的消息
			state.messageQueue.forEach(msg => {
				state.ws.send({
					data: JSON.stringify(msg)
				});
			});
			// 清空队列
			state.messageQueue = [];
		}

	},
	getters: {
		currentSession(state) {
			
			const unreadList = state.chatList.filter(item => item.unreadCount > 0);
			if (unreadList.length > 0) {
				return unreadList.sort((a, b) => b.timestamp - a.timestamp);
			}

		}
	}


};